package cn.zzdt4j.auth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.zzdt4j.auth.mapper.PermissionMapper;
import cn.zzdt4j.auth.model.PermissionInfo;
import cn.zzdt4j.auth.model.biz.permission.PermissionReqDTO;
import cn.zzdt4j.auth.model.biz.permission.PermissionRespDTO;
import cn.zzdt4j.auth.service.PermissionService;
import cn.zzdt4j.common.toolkit.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Permission service impl.
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2023/10/30 0:23
 */
@Service
@AllArgsConstructor
public class PermissionServiceImpl implements PermissionService {

    private final PermissionMapper permissionMapper;

    @Override
    public List<PermissionRespDTO> listPermissionByUserName(String username) {
        LambdaQueryWrapper<PermissionInfo> queryWrapper = Wrappers.lambdaQuery(PermissionInfo.class)
                .eq(PermissionInfo::getUsername, username);
        return BeanUtil.convert(permissionMapper.selectList(queryWrapper), PermissionRespDTO.class);
    }

    @Override
    public void bindingPermissionByUsername(String username, List<PermissionReqDTO> permissionRequestParamList) {
        if (CollectionUtil.isNotEmpty(permissionRequestParamList)) {
            deletePermission(username);
            permissionRequestParamList.forEach(each -> permissionMapper.insert(PermissionInfo.builder().username(username).resource(each.getResource()).action(each.getAction()).build()));
        }
    }

    @Override
    public void deletePermission(String username) {
        permissionMapper.delete(Wrappers.lambdaUpdate(PermissionInfo.class).eq(PermissionInfo::getUsername, username));
    }
}
